<template>
  <div class="phone-management">
    <el-tabs v-model="activeName">
      <el-tab-pane label="设备管理" name="device">
        <!-- 搜索|新增 -->
        <div class="set-parameters">
          <el-input
            v-model="deviceid"
            class="device-wechat-id"
            size="small"
            placeholder="请输入设备号"
            clearable
            minlength="6"
            maxlength="30"
            show-word-limit
          ></el-input>

          <el-input
            v-model="wechatid"
            class="wechat-id-input device-wechat-id"
            size="small"
            placeholder="请输入wxid"
            clearable
            minlength="6"
            maxlength="30"
            show-word-limit
          ></el-input>

          <el-select v-model="isonline" size="small" placeholder="上线状态" filterable clearable>
            <el-option v-for="ols in onlineState" :key="ols.id" :label="ols.label" :value="ols.value"></el-option>
          </el-select>

          <el-select v-model="groupId" size="small" placeholder="请选择分组" filterable clearable style="width: 280px">
            <el-option v-for="group in groupsList" :key="group.id" :label="group.name" :value="group.id"></el-option>
          </el-select>

          <el-button type="primary" size="small" @click="queryDeviceDataByCondition">查询</el-button>
          <el-button type="primary" size="small" @click="showDialog">添加</el-button>
          <el-button type="primary" size="small" @click="addGroupId">批量分组</el-button>
        </div>

        <!-- 信息展示 -->
        <el-table
          ref="multipleTable"
          :data="tableData"
          stripe
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="snumber" label="序号" header-align="center" align="center"></el-table-column>
          <el-table-column prop="deviceid" label="设备号" header-align="center" align="center"></el-table-column>
          <el-table-column prop="wechatid" label="微信id" header-align="center" align="center"></el-table-column>
          <el-table-column prop="wechatnick" label="微信昵称" header-align="center" align="center"></el-table-column>
          <el-table-column prop="groupid" label="所属分组" header-align="center" align="center">
            <template slot-scope="{ row }">
              <span v-text="groupsMap[row.groupid] || row.groupid"></span>
            </template>
          </el-table-column>
          <el-table-column label="手机是否在线" header-align="center" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.isonline === 0" style="color: #67c23a" v-text="'已上线'"></span>
              <span v-else style="color: #f56c6c" v-text="'已下线'"></span>
            </template>
          </el-table-column>
          <el-table-column prop="accountid" label="所属操作员" header-align="center" align="center">
            <template slot-scope="{ row }">
              <el-tag v-for="(ai, index) in row.accountid" :key="index" style="margin: 5px" type="success">
                {{ accountsMap[ai] || ai }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" header-align="center" align="center">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
              <el-button
                size="mini"
                style="background-color: #ff9f00; color: #ffffff"
                type="warning"
                @click="handleDelete(scope.$index, scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          :current-page="pageNo"
          :page-sizes="[20, 40, 60, 80]"
          :page-size="pageSize"
          :pager-count="5"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </el-tab-pane>
      <el-tab-pane label="设备分组" name="group">
        <!-- 搜索|新增 -->
        <div class="set-parameters">
          <el-input
            v-model="groupName"
            class="device-wechat-id"
            size="small"
            placeholder="请输入分组名称"
            clearable
            maxlength="20"
            show-word-limit
          ></el-input>
          <el-button type="primary" size="small" @click="queryGroupDataByName">查询</el-button>
          <el-button type="primary" size="small" @click="addGroup">添加</el-button>
        </div>
        <!-- 数据展示 -->
        <el-table :data="groupData" height="100%" stripe>
          <el-table-column prop="name" label="分组名称" header-align="center" align="center"></el-table-column>
          <el-table-column label="创建时间" header-align="center" align="center">
            <template slot-scope="scope">
              <span v-text="$options.filters.transformTime2Minute(scope.row.createTime)"></span>
            </template>
          </el-table-column>
          <el-table-column label="操作" header-align="center" align="center">
            <template slot-scope="scope">
              <el-button size="mini" @click="updateGroupName(scope.row)">修改</el-button>
              <el-button
                size="mini"
                style="background-color: #ff9f00; color: #ffffff"
                type="warning"
                @click="deleteGroupItem(scope.$index, scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          :current-page="groupPageNo"
          :page-sizes="[20, 40, 60, 80]"
          :page-size="groupPageSize"
          :pager-count="5"
          layout="total, sizes, prev, pager, next, jumper"
          :total="groupTotal"
          @size-change="handleGroupSizeChange"
          @current-change="handleGroupPageChange"
        ></el-pagination>
      </el-tab-pane>
    </el-tabs>

    <el-dialog
      :modal="false"
      append-to-body
      class="add-device-dialog"
      :title="dialogTitle"
      :visible.sync="dialogVisible"
    >
      <el-form ref="ruleForm" :model="deviceForm" :rules="rules">
        <el-form-item label="所属操作员" :label-width="formLabelWidth" prop="accountid">
          <el-select
            v-model="deviceForm.accountid"
            multiple
            placeholder="请选择操作员"
            filterable
            clearable
            style="width: 280px"
          >
            <el-option
              v-for="account in accounts"
              :key="account.id"
              :label="account.account"
              :value="account.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="设备ID" :label-width="formLabelWidth" prop="deviceid">
          <el-input
            v-model="deviceForm.deviceid"
            placeholder="请输入账号名称"
            clearable
            minlength="6"
            maxlength="30"
            show-word-limit
            autocomplete="off"
            style="width: 280px"
          ></el-input>
        </el-form-item>

        <el-form-item label="分组" :label-width="formLabelWidth" prop="groupid">
          <el-select v-model="deviceForm.groupid" placeholder="请选择分组" filterable clearable style="width: 280px">
            <el-option v-for="group in groupsList" :key="group.id" :label="group.name" :value="group.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="序号" :label-width="formLabelWidth" prop="snumber">
          <el-input-number
            v-model="deviceForm.snumber"
            controls-position="right"
            :min="0"
            :max="10000"
          ></el-input-number>
        </el-form-item>

        <el-form-item label="手机别名" :label-width="formLabelWidth" prop="devnickname">
          <el-input
            v-model="deviceForm.devnickname"
            style="width: 280px"
            placeholder="请输入手机别名"
            clearable
            maxlength="30"
            show-word-limit
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="手机品牌" :label-width="formLabelWidth" prop="brand">
          <el-input
            v-model="deviceForm.brand"
            style="width: 280px"
            placeholder="请输入手机品牌"
            clearable
            maxlength="30"
            show-word-limit
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="手机型号" :label-width="formLabelWidth" prop="module">
          <el-input
            v-model="deviceForm.module"
            style="width: 280px"
            placeholder="请输入手机型号"
            clearable
            maxlength="30"
            show-word-limit
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateOrAddDevice">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { queryDevices, deleteDevices, addDevice, updateDevice, groupDevices } from '@/api/admin/device'
import { queryAccountsByCid } from '@/api/httpApiAdmin'
import {
  getAllDeviceGroup,
  getDeviceGroup,
  addDeviceGroup,
  updateDeviceGroup,
  deleteDeviceGroup
} from '@/api/admin/group'

export default {
  name: 'DevicesManagement',
  data() {
    return {
      activeName: 'device',
      tableData: [], // 表格中的数据
      deviceid: '', // 设备号
      groupId: '', // 分组id
      wechatid: '', // 微信id
      accounts: [], // 客服列表
      isonline: '', // 微信在线状态
      onlineState: [
        {
          id: 'isonline0',
          value: 0,
          label: '已上线'
        },
        {
          id: 'isonline1',
          value: 1,
          label: '已下线'
        }
      ], // 微信在线状态列表
      pageNo: 1, // 第几页
      pageSize: 20, // 每页几个数据
      total: 0, // 总数
      dialogTitle: '添加设备',
      dialogVisible: false, // 显示dialog
      formLabelWidth: '120px',
      deviceForm: {
        id: '',
        cid: '',
        deviceid: [], // 设备id（一般为imei）
        accountid: '', // 所属操作员账号id，为空则未分配
        groupid: '', // 分组id
        snumber: 0, // 序号
        devnickname: '', // 设备名称
        brand: '', // 手机品牌
        module: '' // 手机型号
      }, // 表单
      rules: {
        accountid: [{ required: true, message: '请选择操作员', trigger: 'blur' }],
        deviceid: [{ required: true, message: '请输入设备号', trigger: 'blur' }]
      }, // 表单验证

      groupsList: [], // 所属分组
      groupName: '', // 分组名称
      groupData: [], // 分组数据
      groupPageNo: 1, // 第几页
      groupPageSize: 20, // 每页几个数据
      groupTotal: 0, // 总数

      multipleSelection: []
    }
  },
  computed: {
    ...mapState({
      adminInfo: 'adminInfo'
    }),
    accountsMap() {
      const am = {}
      this.accounts.forEach((x) => {
        am[x.id] = x.account
      })
      return am
    },
    groupsMap() {
      const am = {}
      this.groupsList.forEach((x) => {
        am[x.id] = x.name
      })
      return am
    }
  },
  mounted() {
    queryAccountsByCid(this.adminInfo.cid).then((res) => {
      if (res.code === 0) {
        this.accounts = res.data || []
      }
    })
    this.querAllGroup()
    this.queryDeviceData()
    this.queryGroupData()
  },
  methods: {
    // 查询所有的分组数据
    querAllGroup() {
      getAllDeviceGroup(this.adminInfo.cid).then((res) => {
        this.groupsList = res.data || []
      })
    },
    // 按条件查询分组数据
    queryGroupData() {
      getDeviceGroup(this.adminInfo.cid, this.groupName, this.groupPageNo, this.groupPageSize).then((res) => {
        if (res.code === 0) {
          this.groupData = res.data.rows
          this.groupTotal = res.data.records || 0
        }
      })
    },
    // 搜索分组数据
    queryGroupDataByName() {
      if (this.groupName) {
        this.groupPageNo = 1
        this.groupPageSize = 20
      }
      this.queryGroupData()
    },
    // 修改pageSize
    handleGroupSizeChange(val) {
      if (this.pageSize === val) return
      this.groupPageSize = val
      this.queryGroupData()
    },
    // 修改当前页
    handleGroupPageChange(val) {
      this.groupPageNo = val
      this.queryGroupData()
    },
    // 添加分组
    addGroup() {
      this.$prompt('请输入分组名称', '添加分组', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /[\u4e00-\u9fa5_a-zA-Z0-9]{1,50}/,
        inputErrorMessage: '名称格式不正确'
      })
        .then(({ value }) => {
          addDeviceGroup(this.adminInfo.cid, value).then((res) => {
            if (res.code === 0) {
              this.queryGroupData()
            }
          })
        })
        .catch(() => {})
    },
    // 修改分组名称
    updateGroupName(row) {
      this.$prompt('请输入分组名称', '修改分组名称', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: '输入分组名称',
        inputValue: row.name,
        inputPattern: /[\u4e00-\u9fa5_a-zA-Z0-9]{1,50}/,
        inputErrorMessage: '名称格式不正确'
      })
        .then(({ value }) => {
          updateDeviceGroup(row.id, this.adminInfo.cid, value).then((res) => {
            if (res.code === 0) {
              this.queryGroupData()
            }
          })
        })
        .catch(() => {})
    },
    // 删除分组
    deleteGroupItem(index, row) {
      this.$confirm('此操作将删除该分组, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteDeviceGroup(row.id).then((res) => {
            if (res.code === 0) {
              this.queryGroupData()
            }
          })
        })
        .catch(() => {})
    },
    // ==============================================================
    // 分页查询设备数据
    queryDeviceData() {
      queryDevices(
        this.adminInfo.cid,
        this.pageNo,
        this.pageSize,
        this.deviceid,
        this.wechatid,
        this.isonline,
        this.groupId
      ).then((res) => {
        if (res.code === 0) {
          const devicesList = res.data.rows || []
          for (const device of devicesList) {
            device.accountid = device.accountid.split(',')
          }
          this.tableData = devicesList
          this.total = res.data.records || 0
        }
      })
    },
    queryDeviceDataByCondition() {
      if (this.deviceid || this.wechatid || this.isonline !== '' || this.groupId !== '') {
        this.pageNo = 1
        this.pageSize = 20
      }
      this.queryDeviceData()
    },
    // 修改pageSize
    handleSizeChange(val) {
      if (this.pageSize === val) return
      this.pageSize = val
      this.queryDeviceData()
    },
    // 修改当前页
    handleCurrentChange(val) {
      this.pageNo = val
      this.queryDeviceData()
    },
    // 显示dialog
    showDialog() {
      this.resetForm()
      this.dialogTitle = '添加设备'
      this.dialogVisible = true
    },
    // 修改或添加设备
    updateOrAddDevice() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          const { id, deviceid, accountid, groupid, devnickname, brand, snumber } = this.deviceForm
          const cid = this.adminInfo.cid
          const model = this.deviceForm.module
          const accountIdStr = accountid.join(',')

          if (this.dialogTitle === '添加设备') {
            addDevice(cid, deviceid, accountIdStr, groupid, devnickname, brand, model, snumber).then((res) => {
              if (res.code === 0) {
                this.queryDeviceData()
                this.dialogVisible = false
              }
            })
          } else {
            updateDevice(id, cid, deviceid, accountIdStr, groupid, devnickname, brand, model, snumber).then((res) => {
              if (res.code === 0) {
                this.dialogVisible = false
                this.queryDeviceData()
                // this.$message({
                //   type: 'success',
                //   message: '更新成功',
                //   duration: 1000
                // })
              }
            })
          }
        } else {
          return false
        }
      })
    },
    // 重置表单
    resetForm() {
      this.deviceForm = {
        id: '',
        cid: '',
        deviceid: '', // 设备id（一般为imei）
        accountid: '', // 所属操作员账号id，为空则未分配
        groupid: '',
        snumber: 0,
        devnickname: '', // 设备名称
        brand: '', // 手机品牌
        module: '' // 手机型号
      }
    },
    // 显示编辑dialog
    handleEdit(index, row) {
      for (const key in row) {
        if (row.hasOwnProperty(key)) {
          if (key === 'state') {
            this.deviceForm[key] = row[key] === 1
          } else if (key === 'accountid') {
            const aids = []
            row['accountid'].forEach((x) => {
              aids.push(Number(x))
            })
            this.deviceForm['accountid'] = aids
          } else {
            this.deviceForm[key] = row[key]
          }
        }
      }
      this.dialogTitle = '编辑设备'
      this.dialogVisible = true
    },
    // 删除
    handleDelete(index, row) {
      this.$confirm('是否删除设备？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteDevices(row.id).then((res) => {
            if (res.code === 0) {
              const pn = Math.ceil((this.total[this.activeName] - 1) / this.pageSize)
              if (this.pageNo > pn) {
                this.pageNo = pn
              }
              this.queryDeviceData()
              // this.$message({
              //   type: 'success',
              //   message: '删除成功!',
              //   duration: 1000
              // })
            }
          })
        })
        .catch(() => {})
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 批量分组
    addGroupId() {
      const deviceList = this.multipleSelection.map((x) => {
        return x.id
      })
      if (deviceList.length <= 0) {
        this.$alert('至少选中一个设备！', '提示', { type: 'warning' })
        return
      }
      if (!this.groupId) {
        this.$alert('请在左侧选择一个分组！', '提示', { type: 'warning' })
        return
      }
      groupDevices(deviceList.join(','), this.groupId).then((res) => {
        if (res.code === 0) {
          this.groupId = ''
          this.queryDeviceData()
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.phone-management {
  height: 100%;
  display: flex;
  flex-direction: column;

  .set-parameters {
    padding: 10px 5px;
    display: flex;
    align-items: center;
    border-bottom: solid $border-color-1 2px;
    .el-button,
    .wechat-id-input,
    .el-select {
      margin-left: 20px;
    }
    ::v-deep .device-wechat-id {
      width: 220px;
      .el-input__inner {
        width: 220px;
      }
    }
  }

  .el-pagination {
    padding: 5px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-top: solid 1px $border-color-1;
    background-color: white;
  }
  ::v-deep .el-tabs {
    overflow: hidden;
    flex: 1 1 auto;
    display: flex;
    flex-direction: column;
    .el-tabs__header {
      margin: 0;
    }
    .el-tabs__content {
      flex: 1 1 auto;
      .el-tab-pane {
        height: 100%;
        display: flex;
        flex-direction: column;
        .el-table {
          flex: 1 1 auto;
        }
      }
    }
  }
}
</style>
